import { asyncRoutes, constantRoutes } from '@/router'
import store from '@/store'
import { string } from 'clipboard'
// import { getAuthMenu } from '@/api/user'

// 假装fakeRouter是通过后台接口请求回来的数据
// eslint-disable-next-line no-unused-vars
const lawRouters = ["客户管理", "创建客户", "客户列表", "编辑客户", '合同管理', '创建合同', '合同列表', '编辑合同', '案件管理', '民事争议', '创建民事争议', '民事争议列表', '编辑民事争议', '刑事案件', '创建刑事案件', '刑事案件列表', '编辑刑事案件', '非诉讼案件', '创建非诉讼案件', '非诉讼案件列表', '编辑非诉讼案件', '系统设置', '角色管理', '用户管理']

/**
 * 递归遍历初始动态路由数组，去掉没有权限的路由
 * @param routes 路由数组
 */
const recursiveAuthRoutes = (routes) => {
  for (let i = routes.length - 1; i >= 0; i--) {
    if (!lawRouters.includes(routes[i]?.meta?.title)) {
      routes.splice(i, 1)
    } else {
      const childRoutes = routes[i].children
      if (childRoutes) {
        recursiveAuthRoutes(childRoutes)
      }
    }
  }
}
const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      // 先查询后台并返回左侧菜单数据并把数据添加到路由
      // getAuthMenu().then(response => {
      //   if (response.code !== 200) {
      //     alert(JSON.stringify('菜单数据加载异常'))
      //     // throw new Error('菜单数据加载异常')
      //   } else {
      //     // eslint-disable-next-line no-unused-vars
      //     const data = response.data
      //     const loadMenuData = []
      //     Object.assign(loadMenuData, data)
      //     const _asyncRoutes = []
      //     generaMenu(asyncRoutes, loadMenuData, _asyncRoutes)
      //     const accessedRoutes = _asyncRoutes || []
      //     commit('SET_ROUTES', accessedRoutes)
      //     resolve(accessedRoutes)
      //   }
      // })
      // -------------------------- 分隔线 ---------------------------- 
      recursiveAuthRoutes(asyncRoutes)
      commit('SET_ROUTES', asyncRoutes)
      resolve(asyncRoutes)
      // -------------------------- /分隔线 ----------------------------
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
